package com.yinhanshi.s3test.bean;

import android.util.Log;

import java.io.File;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;

/**
 * 标题：用于文件上传请求
 * 作者：yinhanshi .
 * 时间：2020/3/8 .
 */
public class FileRequestBody extends RequestBody {

    private final static String TAG = FileRequestBody.class.getSimpleName();
    /* 上传文件的类型 */
    private MediaType mediaType;
    /* 需要上传的文件 */
    private File file;
    /* 已经发送的字节数 */
    private long writen = 0L;

    /**
     * 构造FileRequestBody
     * @param mediaType     上传文件的类型
     * @param file          上传的文件
     */
    public FileRequestBody(MediaType mediaType, File file) {
        this.mediaType = mediaType;
        this.file = file;
    }

    @Override
    public long contentLength() throws IOException {
        return file.length();
    }

    @Override
    public MediaType contentType() {
        return mediaType;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        BufferedSource bufferedSource = Okio.buffer(Okio.source(file));

        byte[] buffer = new byte[8192];
        long len = 0;

        /**
         * 从文件一次读取8k字节，发送给服务器
         */
        while((len = bufferedSource.read(buffer)) > 0){
            sink.write(buffer, 0, (int) len);
            writen += len;
            /* 这里就可以写一个回调接口，用户监听进度 */
            Log.d(TAG, "writeTo: progress=" + (int)((writen/(float)contentLength()) * 100) + "%");
        }
    }

}
